//
//  TCMeetTabar.swift
//  onemeetingmac
//
//  Created by 张衡 on 2019/12/17.
//  Copyright © 2019 onemeeting. All rights reserved.
//



import Foundation

struct Sour {
    var title:String?
    var imgNom:String
    
    mutating func initTitle(t:String?,imgNom:String) {
        self.title = t
        self.imgNom = imgNom
    }
}

@objc protocol TCMeetTabViewDelegate {
    @objc optional func tcmeetTabar_switch(tatcTabView:TCMeetTabar,index:Int)
}

class TCMeetTabar: NSView {
    
    var isJoin:Bool = false
    let kTabW = CGFloat(100)
    let kTabLW = CGFloat(60)
    
    let leftSours:[Sour] = [
       Sour.init(title: "音频", imgNom: "toolbar_mute_voip_normal"),
       Sour.init(title: "视频", imgNom: "toolbar_stop_video_normal"),
   ]
   
    
    var sours:[Sour] = []
    
    var leftSubView:[TabView] = []
    var centerSubView:[TabView] = []
    
    let audios:[String] = ["aui","设置"]
    let videos:[String] = ["vides1","vides2","设置"]
    
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }
    
    convenience init(isJoin:Bool) {
        self.init()
        self.isJoin = isJoin
        self.setupData()
        self.setupUI()
        self.loadData()
        self.addNot()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func addNot() {
        NotificationCenter.default.addObserver(self, selector: #selector(userStatuChange(not:)), name: MTUserStateNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(capAudio(not:)), name: MTCapAudioNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(liveStatu(not:)), name: MTLIVENotification, object: nil)
        
    }
    
    func loadData() {
        let isMute = MTNot.getLocalMute()
        (self.leftSubView[0].list.custom as? VulameView)?.isMute = isMute
        let mutetitle = isMute ? "解除静音":"静音"
        self.leftSubView[safe:0]?.title.stringValue = mutetitle
        
        let image = Td.sh().lc.isVdOpen ? "icon_meeting_video":"icon_meeting_video_mute"
        self.leftSubView[safe:1]?.icon.image = NSImage.image(name:image)
        let title = Td.sh().lc.isVdOpen ? "关闭视频":"开启视频"
        self.leftSubView[safe:1]?.title.stringValue = title

        if self.isJoin == false {
            let open = TXLiteManager.shared().pushType == .live ? "开启直播":"开启录制"
            if let sub = self.centerSubView[safe:4] {
                sub.title.stringValue = open
                
                let image = TXLiteManager.shared().isLiving ? "toolbar_rtmp_stop":"toolbar_rtmp_start"
                sub.icon.image = NSImage.image(name:image)
            }
            
        }
        
        
    }
    
    func setupData() {
        if self.isJoin  {
            self.sours = [
                //Sour.init(title: "邀请", imgNom: "toolbar_participant_press"),
                Sour.init(title: "参会者", imgNom: "icon_presons"),
                Sour.init(title: "共享屏幕", imgNom: "toolbar_share_normal"),
                Sour.init(title: "聊天", imgNom: "icon_meeting_attendee"),
                Sour.init(title: "设置", imgNom: "icon_meeting_more")
            ]
        }else {
            self.sours = [
                //Sour.init(title: "邀请", imgNom: "toolbar_participant_press"),
                Sour.init(title: "参会者", imgNom: "icon_presons"),
                Sour.init(title: "共享屏幕", imgNom: "toolbar_share_normal"),
                Sour.init(title: "聊天", imgNom: "icon_meeting_attendee"),
                Sour.init(title: "设置", imgNom: "icon_meeting_more"),
                Sour.init(title: "开启直播", imgNom: "toolbar_rtmp_start")
            ]
        }
    }
    
    func setupUI() {
        self.wantsLayer = true
        self.layer?.backgroundColor = color_gray(53).cgColor
        
        self.addSubview(leftView)
        leftView.snp.makeConstraints { (make) in
            make.width.equalTo(self.getSourWidth(sours: self.leftSours))
            make.height.equalToSuperview()
            make.left.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        self.leftSubView = self.initLeftTabs(inView: self.leftView)
        
        
        self.addSubview(exitBtn)
        exitBtn.snp.makeConstraints { (make) in
            make.width.equalTo(82)
            make.height.equalTo(32)
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        
        self.addSubview(centerBgView)
        centerBgView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        
        centerBgView.addSubview(centerView)
        let centerWidth = CGFloat(self.sours.count)*kTabW
        centerView.snp.makeConstraints { (make) in
            make.width.equalTo(centerWidth)
            make.centerX.equalToSuperview().offset(30)
            make.height.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        self.centerSubView = self.initTabs(inView: self.centerView)
        
        self.centerSubView[0].addSubview(handButtom)
        handButtom.snp.makeConstraints { (make) in
            make.width.equalTo(25)
            make.height.equalTo(25)
            make.right.equalTo(-2)
            make.top.equalTo(2)
        }
    }
    
    
    
    lazy var leftView: NSView = {
        let view = NSView.init()
        return view
    }()
    
    func initLeftTabs(inView:NSView) -> [TabView]{
        var tabs:[TabView] = []
        for (inx,val) in leftSours.enumerated() {
            var view:TabView?
            var group:TabGroup = TabGroup(image: val.imgNom, title: val.title)
            switch inx {
            case 0:
                let vulame = VulameView.init(size: CGSize.init(width: 30, height: 30))
                group.custom = vulame
                view = TabView.init(type: TabType.custom, list: group)
            default:
                view = TabView.init(list: group)
            }
            view?.tag = 100+inx
            view!.delegate = self
            view!.hasRight = true
            inView.addSubview(view!)
            tabs.append(view!)
            
            
            view!.snp.makeConstraints { (make) in
                make.height.equalToSuperview()
                make.top.equalToSuperview()
                make.width.equalTo(kTabW)
                if inx == 0 {
                    make.left.equalTo(0)
                }else {
                    make.left.equalTo(tabs[inx-1].snp.right)
                }
           }
        }
        return tabs
    }
    
    lazy var centerBgView: NSView = {
        let view = NSView.init()
        return view
    }()
    
    lazy var centerView: NSView = {
        let view = NSView.init()
        return view
    }()
    
    
    func getSourWidth(sours:[Sour]) -> CGFloat{
        var zoon:CGFloat = 0
        sours.forEach { (sr) in
            let width = sr.title==nil ? 0:kTabW
            zoon += width
        }
        return zoon
    }
    
    func initTabs(inView:NSView) -> [TabView]{
        inView.layoutSubtreeIfNeeded()
        let zoon = self.getSourWidth(sours: sours)
        let leftx = (inView.frame.width-zoon)/2
        var tabs:[TabView] = []
        for (inx,val) in sours.enumerated() {
            let view = TabView.init(list: TabGroup.init(image: val.imgNom, title: val.title))
            view.delegate = self
            view.tag = 200+inx
            view.hasRight = inx == 1
            inView.addSubview(view)
            tabs.append(view)
            view.snp.makeConstraints { (make) in
                make.height.equalToSuperview()
                make.width.equalTo(kTabW)
                make.top.equalToSuperview()
                if inx == 0 {
                    make.left.equalTo(leftx)
                }else {
                    make.left.equalTo(tabs[inx-1].snp.right)
                }
            }
        }
        return tabs
    }
    
    lazy var handButtom: NSImageView = {
        let imageV = NSImageView.init(image: NSImage.image(name:"icon_adc_hand")!)
        imageV.isHidden = true
        return imageV
    }()
    
    lazy var exitBtn: ZHButton = {
        let btn = ZHButton()
        btn.zh_title = "离开会议"
        btn.zh_font = NSFont.systemFont(ofSize: 14)
        btn.normalColor = NSColor.white
        btn.selectedColor = NSColor.white
        btn.hoverColor = NSColor.white
        btn.highlightColor = NSColor.white
        btn.backgroundNormalColor = color_red85
        btn.backgroundSelectedColor = color_red85
        btn.backgroundHoverColor = color_red85.withAlphaComponent(0.8)
        btn.backgroundHighlightColor = color_red85.withAlphaComponent(0.8)
        btn.target = self
        btn.action = #selector(exitBtn(senber:))
        btn.hasBorder = true
        btn.zh_cornerRadius = 6
        return btn
    }()
    
}

//MARK: - 点击事件
extension TCMeetTabar:TabViewDelegate {
    func tabView_rightButtomAction(tab:TabView) {
        
        switch tab.tag {
        case 100:
            self.audioListAction(sender: tab)
        case 101:
            self.cameraListAction(sender: tab)
        case 201:
            self.shareListAction()
            tab.rightButtom.backgroundViewColor = NSColor.clear
        default:
            break
        }
    }
    
    func tabView_mouseDown(event: NSEvent, senber: TabView) {
        switch senber.tag {
        case 100:
            self.audioAction()
        case 101:
            self.cameraAction()
        case 200:
            self.memberAction()
        case 201:
            self.shareAction()
        case 202:
            self.chatAction()
        case 203:
            self.settingAction()
        case 204:
            self.rtmpAction()
        default:
            break
        }
    }
    
    func shareListAction() {
        if let inWindow = self.jk_viewcontroller()?.view.window {
            let window = NSWindow.init(contentViewController: TDSdSetViewController())
            window.orderInFont(onWindow: inWindow, sender: nil)
        }
    }
    
    @objc func exitBtn(senber:NSButton) {
        AsSheet.exitRoom()
    }
}

extension TCMeetTabar {
    func settingAction()  {
        let window = STWindow.init(contentViewController: TRCTSetViewController())
        window.orderInFont(onWindow: self.window, sender: nil)
    }
    
    func rtmpAction() {
        if Td.sh().lc.isVdOpen == false {
            show_msg("请保持本地摄像头开启，否则推流会失败")
            return
        }
        TXLiteManager.shared().isLiving = !TXLiteManager.shared().isLiving
        MTNot.postRTMPLive()
        
    }
    
    func shareAction() {
        if Td.sh().cloud.disSd == false || String.isHostId() {
            if Td.sh().sd.isSding == true {
                show_msg("已有参会者开启共享")
            }else {
                if String.isHostId() || String.isFocusId() {
                    let window = NSWindow.init(contentViewController: TCSdColloctViewController())
                    window.orderInFont(onWindow: self.window, sender: nil)
                }else {
                    show_msg("只有主持人和焦点才能开启共享！")
                }
            }
        }else {
            show_msg("主持人已经禁止共享")
        }
    }
    
    func chatAction() {
        if Td.fullScreen {
            let vc = TCMeetUSEREngViewController.init(isStand: true,selectInt: 1)
            let window = NSWindow.init(contentViewController: vc)
            window.orderInFont(onWindow: self.window, sender: nil)
        }else {
            Td.sh().isStand = false
            Td.sh().hasUser = !Td.sh().hasUser
            guard let vc = NSWindow.lfind(anyClass: TCMeetUSEREngViewController.classForCoder()) else {
                NotificationCenter.default.post(name: MTHasUserVcNotification, object: (Td.sh().hasUser,1))
                return
            }
            vc.view.window?.collectionBehavior = NSWindow.CollectionBehavior.canJoinAllSpaces
        }
    }
    
    func memberAction() {
        if Td.fullScreen {
            let vc = TCMeetUSEREngViewController.init(isStand: true)
            let window = NSWindow.init(contentViewController: vc)
            window.orderInFont(onWindow: self.window, sender: nil)
        }else {
            Td.sh().isStand = false
            Td.sh().hasUser = !Td.sh().hasUser
            guard let vc = NSWindow.lfind(anyClass: TCMeetUSEREngViewController.classForCoder()) else {
                NotificationCenter.default.post(name: MTHasUserVcNotification, object: (Td.sh().hasUser,0))
                return
            }
            vc.view.window?.collectionBehavior = NSWindow.CollectionBehavior.canJoinAllSpaces
        }
    }
    
    func invateAction(sender:TabView) {
        let window = NSWindow.init(contentViewController: ShareViewController.init(appearance: DSAppearance.dark))
        window.lorderFront(nil)
        let yellowPoint = NSPoint(x: 0, y: sender.frame.height+10)
        let pointInWindow = sender.convert(yellowPoint, to: nil)
        let pointOnScreen = sender.window?.convertToScreen(NSRect.init(origin: pointInWindow, size: CGSize.zero)).origin ?? .zero
        window.setFrameOrigin(pointOnScreen)
    }
    
    func audioAction() {
        if Td.sh().cloud.isALLMute == false || String.isHostId() {
            Td.sh().lc.isMute = !Td.sh().lc.isMute
            MTNot.postNotMute()
        }else {
            show_msg("需要主持人解除全体静音")
        }
    }
    
    func audioListAction(sender:TabView) {
        let spList =  TXLiteManager.shared().getSpeakerDevicesList()! as [AnyObject]
        let micList =  TXLiteManager.shared().getMicDevicesList()! as [AnyObject]
        let baList:[String] = ["音频选项"]
        let menuVc = DeviceViewController()
        menuVc.setData(speakerList: spList, micList: micList, cameraList: [], basicList: baList)
        let lk = Lk.create(controller: menuVc)
        lk.show(relativeTo: CGPoint.init(x: -4, y: -5), of: sender.rightButtom, direccion: LDireccion.T2L) {
            sender.rightButtom.backgroundViewColor = NSColor.clear
        }
    }
    
    func cameraAction() {
        if TXLiteManager.shared().isLiving == true && Td.sh().lc.isVdOpen == true {
            let controller =  KlViewController.init(title: "提示", massage: "当前正在直播中，如果关闭本地视频画面会导致推流失败，你是否继续关闭？", buttomTitles: ["取消","继续"], indexBlock: { (index, control) in
                if index == 1 {
                    self.doCameraAction()
                }
            }, navBlock: nil)
            let window = NSWindow.init(contentViewController: controller)
            window.makeKeyAndOrderFront(nil)
        }else {
            self.doCameraAction()
        }
    }
    
    func doCameraAction() {
        if TCGirdRender.shared().current() != nil {
            Td.sh().lc.isVdOpen = !Td.sh().lc.isVdOpen
            let isVdOpen = Td.sh().lc.isVdOpen
            MTNot.postNotVdOpen(isok: isVdOpen)
        }
    }
    
    func cameraListAction(sender:TabView) {
        let camList =  TXLiteManager.shared().getCameraDevicesList()! as [AnyObject]
        let baList:[String] = ["视频选项"]
        let menuVc = DeviceViewController()
        menuVc.setData(speakerList: [], micList: [], cameraList: camList, basicList: baList)
        let lk = Lk.create(controller: menuVc)
        lk.show(relativeTo: CGPoint.init(x: -4, y: -5), of: sender.rightButtom, direccion: LDireccion.T2L) {
            sender.rightButtom.backgroundViewColor = NSColor.clear
        }
    }
    
    
    func readHands() {
        self.handButtom.isHidden = Td.hands.count == 0
    }
}

//MARK:- 通知
extension TCMeetTabar {
    @objc func capAudio(not:Notification) {
        guard let volume = not.object as? CGFloat else {
            return
        }
        if let view = (self.leftSubView[0].list.custom as? VulameView) {
            if view.isMute == false {
                view.value = volume/100
            }
        }
    }
    
    @objc func liveStatu(not:Notification) {
        if let string = not.object as? String {
            if string == ReloadNotification {
                let isLiving = TXLiteManager.shared().isLiving
                let image = isLiving ? "toolbar_rtmp_stop":"toolbar_rtmp_start"
                self.centerSubView[safe:4]?.icon.image = NSImage.image(name:image)
                let title = isLiving ? "关闭":"开启"
                let type = TXLiteManager.shared().pushType == .live ? "直播":"录制"
                self.centerSubView[safe:4]?.title.stringValue = title+type
            }
        }
    }
    
    @objc func userStatuChange(not:Notification) {
        guard let mode = not.object as? UserMode else {
            return
        }
        if mode.userId == nil {
            if let isMute = mode.isMute {
                (self.leftSubView[0].list.custom as? VulameView)?.isMute = isMute
                TXLiteManager.shared().muteLocalAudio(isMute)
                let mutetitle = isMute ? "解除静音":"静音"
                self.leftSubView[safe:0]?.title.stringValue = mutetitle
            }
            
            if let isVdOpen = mode.isVdOpen {
                Td.sh().lc.isVdOpen = isVdOpen
                let image = isVdOpen ? "icon_meeting_video":"icon_meeting_video_mute"
                self.leftSubView[safe:1]?.icon.image = NSImage.image(name:image)
                let title = isVdOpen ? "关闭视频":"开启视频"
                self.leftSubView[safe:1]?.title.stringValue = title
                if isVdOpen == true {
                    TXLiteManager.shared().startLocalPreview(view: TCGirdRender.shared().current()!.videoView)
                }else {
                    TXLiteManager.shared().stopLocalPreview()
                }
            }
        }
    }
}

extension TCMeetTabar {
    func showBarrge() {
        let view = InputView.init(type: 1)
        view.confirmClick = { text in
            MTNot.postNotBarrge(text: text)
            IMcmd.shared.barrage(txt: text)
            Dialog.shared.dismiss()
        }
        Dialog.shared.initlize(title: "发送弹幕")
        Dialog.shared.addCont(view: view, height: 240)
        Dialog.shared.containerWidth = 500
        Dialog.shared.show()
    }
}

extension NSWindow {
    class func lfind(anyClass:AnyClass) -> NSViewController? {
        for (_,wind) in NSApplication.shared.windows.enumerated() {
            if let isok = wind.contentViewController?.isKind(of: anyClass) {
                if isok == true {
                    return wind.contentViewController
                }
            }
        }
        return nil
    }
    
    class func lrfind(anyClass:AnyClass) -> NSWindow? {
        for (_,wind) in NSApplication.shared.windows.enumerated() {
            if let isok = wind.contentViewController?.isKind(of: anyClass) {
                if isok == true {
                    return wind
                }
            }
        }
        return nil
    }
    
    func addShareChildWindow(_ childWin: NSWindow, ordered place: NSWindow.OrderingMode) {
        if let controller = childWin.contentViewController {
            let first = self.childWindows?.first(where: { (win) -> Bool in
                return win.contentViewController?.isKind(of: controller.classForCoder) == true
            })
            
            if first != nil {
                first?.orderFront(nil)
            }else {
                self.addChildWindow(childWin, ordered: place)
            }
        }
    }
}


